package fw_socketio

import (
	"github.com/gin-gonic/gin"
	"github.com/zishang520/socket.io/v2/socket"
	"log"
)

func middle(client *socket.Socket, e func(*socket.ExtendedError)) {
	name, ok := client.Handshake().Query["name"]
	if !ok {
		// break, how to jump out of this logic
		e(socket.NewExtendedError("name err", nil))
		return
	}
	// next
	log.Println("name==:", name)
}
func SocketIoInit(r *gin.Engine) {
	io := socket.NewServer(nil, nil)
	// use Use funciton or in the second parameter of the Of method
	io.Of("/iot", nil).Use(middle).On("connection", func(clients ...any) {
		client := clients[0].(*socket.Socket)
		client.On("ping", func(datas ...any) {
			log.Println("heart")
			client.Emit("pong", "pong")
		})
		client.On("disconnect", func(...any) {
			log.Println("disconnect")
		})
	})
	sock := io.ServeHandler(nil)
	r.GET("/socket.io/", gin.WrapH(sock))
	r.POST("/socket.io/", gin.WrapH(sock))
}
